package com.itsxb.listener;

import cn.dev33.satoken.secure.BCrypt;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itsxb.constants.Constants;
import com.itsxb.pojo.domain.Login;
import com.itsxb.properties.AdminProperties;
import com.itsxb.service.ILoginService;
import com.itsxb.service.impl.LoginServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;

import java.util.Date;

@Component
public class MyApplicationListener implements ApplicationListener<ContextRefreshedEvent> {
    @Autowired
    private LoginServiceImpl loginService;

    @Autowired
    private AdminProperties adminProperties;

    @Value("${fccar.wechat.default-avatar}")
    private String defaultAvatar;
    @Override
    public void onApplicationEvent(ContextRefreshedEvent event) {
        //监听器中实现的业务逻辑 当监听到ContextRefresherEvent事件完成之后，通过loginService来创建管理员
        //说白了就是在调用LoginServiceImpl中的saveLogin来创建管理员
        Login login = loginService.getOne(new LambdaQueryWrapper<Login>().eq(Login::getUsername, "admin"));
        if(ObjectUtils.isEmpty(login)){
            initLogin();
        }

    }
    //大部分的属性尽量不要写死
    private void initLogin() {
        Login login = new Login();
        //不要写死 从application中获取
        login.setUsername(adminProperties.getDefaultUsername());
        String hashpw = BCrypt.hashpw(adminProperties.getDefaultPassword(), BCrypt.gensalt());
        login.setPassword(hashpw);
        //不能写死
        login.setType(Constants.Login.TYPE_ADMIN);
        login.setEnabled(true);
        //从application中获取
        login.setAvatar(defaultAvatar);
        login.setAdmin(true);
        login.setNickName(adminProperties.getDefaultUsername());
        //admin 需要openId吗？ 不需要为什么  我还是不来OpenId到底干什么的
//        login.setOpenId();
        login.setName(adminProperties.getDefaultUsername());
        login.setCreateTime(new Date());
        //只是设置了数据 没有保存 无效
        loginService.save(login);

    }
}
